$.getScript(contextPath + "/js/echarts.min.js", function () {
    window.createWaveform();
});

/***
 * 绘制洞察结果统计信息表（数值，名词）
 */
window.createResTableInfo1 = function (info, parentEle, nodeType) {
    var rowNum = info.rowNum;
    var columnNum = info.columnNum;
    var resultTableDataInfo = info.resultStatisticData;
    var resultTableDataInfoNom = info.resultStatisticDataNom;
    var nodeConfigId = info.nodeConfigId;
    //处理对于空数据集的统计信息
    if (rowNum && rowNum > 0) {
        var fTypeSelV = TempoMineMetaUtils.getFieldTypeSelectValue();
        var colsInfo = $("<br/><span class='colsInfo' style='display: block;margin-left:10px;margin-bottom:10px;'>" + TempoUtils.locale("mine.shuchushujutongji") + rowNum + TempoUtils.locale("mine.hang") + columnNum + TempoUtils.locale("mine.lie") + "</span>").appendTo(parentEle);
        var table = $('<table class="tempo-mine-insight-table"/>').appendTo(parentEle);
        // 为了保证历史流程洞察兼容，在这里增加一个标识变量，如果值是true表示是历史流程，如果值为false表示新执行的流程
        var isHistoryFlag = true;
        if ((resultTableDataInfo && resultTableDataInfo.length > 0) || (resultTableDataInfoNom && resultTableDataInfoNom.length > 0)) {
            if (resultTableDataInfo && resultTableDataInfo.length > 0) {
                if (resultTableDataInfo[0] && resultTableDataInfo[0].length >= 9) {
                    isHistoryFlag = false;
                }
            } else if (resultTableDataInfoNom && resultTableDataInfoNom.length > 0) {
                if (resultTableDataInfoNom[0] && resultTableDataInfoNom[0].length >= 9) {
                    isHistoryFlag = false;
                }
            }
        } else {
            return;
        }
        var arr = ['attr', 'type', 'hiatusVal', 'histogram', 'min', 'max', 'uniquenums', 'average', 'munPercent'];
        if (isHistoryFlag) {
            arr = ['attr', 'type', 'hiatusVal', 'histogram', 'min', 'max', 'munPercent'];
        }
        var str = '';
        arr.forEach(function (item) {
            str += "<th>" + TempoUtils.locale("mine.mine_" + item) + "</th>";
        })
        $('<thead><tr>' + str + '</tr></thead>').appendTo(table);
        var tbody = $('<tbody/>').appendTo(table);
        for (var i = 0; i < resultTableDataInfo.length; i++) {
            var tr = "<tr>";
            var data = resultTableDataInfo[i];
            var row = TempoUtils.clone(data);
            var dataStr = "";
            var histomId = "a" + TempoUtils.uuid();
            for (var j = 0; j < row.length; j++) {
                if (j == 0) {
                    var newMetaName = TempoUtils.locale(nodeConfigId + "." + nodeConfigId + "_" + row[j]);
                    if (typeof (newMetaName) != "undefined") {
                        row[j] = newMetaName;
                    }
                    //字段名进行转义，防止xss注入
                    row[j] = TempoMineUtils.encodeHTML(row[j]);
                }
                if (j == 1) {
                    row[j] = fTypeSelV[row[j]];
                }
                if (j == 2) {
                    row[j] = parseInt(row[j]);
                }
                if (isHistoryFlag) {
                    if (j >= 4 && j <= 6) {
                        // 若当前值是数字，则赋值
                        if ($.isNumeric(row[j])) {
                            row[j] = TempoMineUtils.format(row[j]);
                        } else {
                            row[j] = "";
                        }
                    }
                } else {
                    if ((j >= 4 && j <= 5) || j >= 7) {
                        if (j == 7) {
                            row[j] = row[j] / rowNum;
                        }
                        // 若当前值是数字，则赋值
                        if ($.isNumeric(row[j])) {
                            row[j] = TempoMineUtils.format(row[j]);
                        } else {
                            row[j] = "";
                        }
                    }
                }

                if (j != 3) {
                    tr += "<td>" + row[j] + "</td>";
                } else {
                    tr += "<td style='width:400px;'><div id='" + histomId + "' style='width:400px;height:160px;'></div></td>";
                    dataStr = row[j];
                }
            }
            tr += "</tr>";
            $(tr).appendTo(tbody);
            TempoMineChartUtils.drawHistogramVeriticalNum(dataStr, histomId, 400, 160);
        }
        if (resultTableDataInfoNom) {
            for (var i = 0; i < resultTableDataInfoNom.length; i++) {
                var tr = "<tr>";
                var data = resultTableDataInfoNom[i];
                var dataStr = "";
                var row = TempoUtils.clone(data);
                var histomId = "a" + TempoUtils.uuid();
                for (var j = 0; j < row.length; j++) {
                    if (j == 0) {
                        var newMetaName = TempoUtils.locale(nodeConfigId + "." + nodeConfigId + "_" + row[j]);
                        if (typeof (newMetaName) != "undefined") {
                            row[j] = newMetaName;
                        }
                        //字段名进行转义，防止xss注入
                        row[j] = TempoMineUtils.encodeHTML(row[j]);
                    }
                    if (j == 1) {
                        row[j] = fTypeSelV[row[j]];
                    }
                    // 最小/最少，最大/最多需要判断是否为对象类型，若是，则需要转换为字符串
                    if (row[4] && ($.isPlainObject(row[4]) || $.isArray(row[4]))) {
                        row[4] = JSON.stringify(row[4]);
                    }
                    if (row[5] && ($.isPlainObject(row[5]) || $.isArray(row[5]))) {
                        row[5] = JSON.stringify(row[5]);
                    }

                    if (j == (row.length - 1)) {
                        var title = row[j];
                        var moreStr = row[j];
                        tr += "<td " + (title ? ("title='" + TempoMineUtils.encodeHTML(title) + "'") : "") + ">" + moreStr + "</td>";
                    } else if (j != 3) {
                        tr += "<td>" + row[j] + "</td>";
                    } else {
                        tr += "<td style='width:400px;'><div id='" + histomId + "' style='width:400px;height:160px;'></div></td>";
                        dataStr = row[j];
                    }
                }
                tr += "</tr>";
                $(tr).appendTo(tbody);
                TempoMineChartUtils.drawHistogramHorizontalChar(dataStr, histomId, 400, 160);
            }
        }
    } else {
        $("<br/><span class='colsInfo' style='display: block;margin-left:10px;margin-bottom:10px;'>" + TempoUtils.locale("mine.shuchushujutongji") + rowNum + TempoUtils.locale("mine.hang") + columnNum + TempoUtils.locale("mine.lie") + "</span>").appendTo(parentEle);
    }

}

/**
 * 处理输出数据列多的情况，如果列数超过17列，则只显示前后8列数据，中间用...显示
 */
window.doResultTableData = function (resultTableData) {
    var ansTableData = [];
    if (resultTableData && resultTableData.length > 0) {
        var lineData = resultTableData[0];
        // 如果输出数据列超过17列，则只显示前后8列数据，中间用...显示
        if (lineData && lineData.length > 17) {
            for (var i = 0; i < resultTableData.length; i++) {
                var rowData = resultTableData[i];
                var newRowData = rowData.slice(0, 8);
                newRowData.push("...");
                newRowData = newRowData.concat(rowData.slice(-8));
                ansTableData.push(newRowData);
            }
        } else {
            ansTableData = resultTableData;
        }
    }
    return ansTableData;
}

/**
 * 绘制洞察输入和结果的表
 * @param insightData 数据
 * @param parentEle div
 * @param type 创建表的节点类型
 */
window.createResTable = function (insightData, parentEle) {
    if (insightData.type == "user_defined") {
        if (!insightData.resultTableData) {
            insightData.resultTableData = insightData.resultDataset;
        }
    }
    var resultTableData = doResultTableData(insightData.resultTableData);
    var nodeConfigId = insightData.nodeConfigId;
    var vectorUDTIndexArr = [];
    var metaNames = resultTableData[1];
    var newMetaNames = [];
    for (var i = 0; i < metaNames.length; i++) {
        var metaName = metaNames[i];
        // 如果在国际化文件中有此国际化项，则使用国际化项的值
        var newMetaName = TempoUtils.locale(nodeConfigId + "." + nodeConfigId + "_" + metaName);
        if (typeof (newMetaName) == "undefined") {
            newMetaNames.push(metaName);
        } else {
            newMetaNames.push(newMetaName);
        }
    }
    var metaTypes = resultTableData[0];
    if (metaTypes && metaTypes.length && metaTypes.length > 0) {
        for (var index = 0; index < metaTypes.length; index++) {
            if (metaTypes[index].indexOf(window.mineConstant.ML_VECTOR_TYPE) != -1) {
                vectorUDTIndexArr.push(index);
            }
        }
    }
    var meta = [];
    for (var i = 0; i < resultTableData.length; i++) {
        if (i != 1) {
            var dataItem = resultTableData[i];
            if (dataItem.length > 0 && dataItem[0] != window.mineConstant.OUTPUT_DATASET_END_FLAG) {
                for (var j = 0; j < vectorUDTIndexArr.length; j++) {
                    var vectorUDTItem = dataItem[vectorUDTIndexArr[j]];
                    if ($.isArray(vectorUDTItem)) {
                        for (var k = 0; k < vectorUDTItem.length; k++) {
                            if (typeof vectorUDTItem[k] == 'number') {
                                vectorUDTItem[k] = parseFloat((vectorUDTItem[k]).toFixed(4));
                            }
                        }
                    } else {
                        try {
                            var vectorUDTArray = JSON.parse(vectorUDTItem);
                            if ($.isArray(vectorUDTArray)) {
                                for (var k = 0; k < vectorUDTArray.length; k++) {
                                    vectorUDTArray[k] = parseFloat((vectorUDTArray[k]).toFixed(4));
                                }
                                dataItem[vectorUDTIndexArr[j]] = "[" + vectorUDTArray.join(",") + "]";
                            }
                        } catch (e) {
                        }
                    }
                }
            }
            meta.push(dataItem);
        }
    }
    //添加节点洞察数据集为空显示提示
    if (meta && meta.length <= 1) {
        TempoMineInsightUtils.showNullDatasetInsight(parentEle);
    }
    //处理
    var resTable = TempoMineUtils.buildTableByMeta(meta, newMetaNames, "tempo-mine-insight-table", "", insightData.flag);
    if (insightData.flag == window.mineConstant.PORT_SIGNAL && insightData.afterLength) {
        $('<span style="cursor: pointer;display: inline;font-size:14px;margin-left: 10px;" id="rowNumberStat' + TempoUtils.uuid() + '">共' + (insightData.afterLength) + '行</span>').appendTo(parentEle);
        resTable.css("margin-top", "10px");
    }
    resTable.appendTo(parentEle);
}
//信号分割波形图数据格式处理
window.createFormatData = function (insightData) {
    var formatData = {};
    var signalDatas = insightData.waveFromData;
    var outputDataLength = 10;
    if (signalDatas.length < 10) {
        outputDataLength = signalDatas.length;
    }
    var outputDataArray = [];
    var outputNameArray = [];
    var outputSignalLength = [];
    for (var i = 0; i < outputDataLength; i++) {
        var data = signalDatas[i].split(";");
        var arrayData = data[3].substring(1, data[3].length - 1).split(",")
        outputDataArray.push(arrayData);
        outputNameArray.push(data[0].substring(data[0].lastIndexOf("/") + 1));
        outputSignalLength.push(data[4]);
    }
    formatData.outputDataArray = outputDataArray;
    formatData.outputNameArray = outputNameArray;
    formatData.outputSignalLength = outputSignalLength;
    return formatData;
}
/**
 * 创建波形图
 * @param formatData 构造的二维数组
 *                     里面是一个formatData.outputDataArray保存数据
 *                     里面是一个formatData.outputNameArray保存文件名称
 *                     outputDataArray和outputNameArray都是数组格式
 * @param parentEle  放置波形图的父容器
 * @param nodeId  节点的id，防止波形图id重复(不加会导致导出word页面出现问题)，拼接到div的id里面
 */
window.createWaveform = function (formatData, parentEle, nodeId) {
    if ($.isEmptyObject(formatData)) {
        return;
    }
    //清空以前的数据
    $("#rs").empty();
    for (var j = 0; j < formatData.outputDataArray.length; j++) {
        var marginTop = "-15px";
        if (j != 0) {
            marginTop = "-80px";
        }
        $("<div id='waveformDiv" + j + "_" + nodeId + "' style='width:1200px;height: 350px;margin-top: " + marginTop + "'></div>").appendTo(parentEle);
        var myChart = echarts.init(document.getElementById("waveformDiv" + j + "_" + nodeId));
        /**$(document.getElementById("waveformDiv" + j + "_" + nodeId)).attr("data", formatData.outputNameArray[j]);
         myChart.on("mousemove", function (params, formatData) {
			var id = document.getElementById("extension");
			if(!id) {
				//在body上挂载一个div，用来显示X轴悬浮的标签
				var div = document.createElement('div');
				div.id = 'extension';
				div.style.display = 'none';
				document.body.append(div);
			}
			if(params.componentType == "title") {
				var extension = document.getElementById('extension');
				var title = $('#'+params.event.target.__zr.dom.id).attr("data");
				title=title.substring(0,99)+"</br>"+title.substring(100);
				extension.innerHTML = title;
				extension.style.position = "absolute";
				extension.style.display = 'block';
				extension.style.top = params.event.event.clientY + 10 +  'px';
				extension.style.left = params.event.event.clientX + 20 + 'px';
				extension.style.fontSize = '8px';
				extension.style.borderStyle = 'solid';
				extension.style.whiteSpace = 'nowrap';
				extension.style.zIndex = '9999999';
				extension.style.backgroundColor = 'rgb(50, 50, 50, 0.7)';
				extension.style.borderWidth = '0px';
				extension.style.borderColor = 'rgb(51, 51, 51)';
				extension.style.borderRadius = '4px';
				extension.style.color = 'rgb(255, 255, 255)';
				extension.style.font = '14px / 21px "Microsoft YaHei';
				extension.style.padding = '5px';
				extension.style.pointerEvents = 'none';
			}
		});
         myChart.on("mouseout", function (params) {
			var extension = document.getElementById("extension");
			extension.innerHTML = '';
			extension.style.display = 'none';
		});*/
        var xdata = [];
        var ydata = [];
        var series = [];
        var yaxis = [];
        var length = formatData.outputDataArray[j].length;
        //把信号长度分为数据个数平均值然后递增
        var value = formatData.outputSignalLength[j] / length;
        var intValue = parseInt(value);
        var initData = intValue;
        for (var k = 0; k < length; k++) {
            if (formatData.outputDataArray[j][k] == undefined || formatData.outputDataArray[j][k] == null || formatData.outputDataArray[j][k] == "") {
                ydata.push(0);
            } else {
                ydata.push(formatData.outputDataArray[j][k]);
            }
            if (k == 0) {
                xdata.push(0);
            } else if (k == 1) {
                xdata.push(intValue);
            } else if (k == length - 1) {
                xdata.push(formatData.outputSignalLength[j]);
            } else {
                initData = initData + intValue;
                xdata.push(initData);
            }
        }


        yaxis.push({
            type: 'value',
            splitArea: {
                show: true,
                interval: 0,
                areaStyle: {
                    color: ['black']
                }
            },
            axisLabel: {
                formatter: function (value) {
                    return value
                }
            }
        })
        series.push({
            name: formatData.outputNameArray[j],
            type: 'line',
            smooth: true,
            symbol: "none",
            yAxisIndex: 0, //属性，归属右侧y轴
            itemStyle: {
                color: "#00ff43"
            },
            data: ydata,
        });
        // 指定图表的配置项和数据
        var option = {
            title: {
                show: true,
                text: formatData.outputNameArray[j],
                textStyle: {
                    color: 'black',
                    fontStyle: 'normal',
                    fontWeight: 'normal',
                    fontSize: 14,
                    lineHeight: 14
                },
                textAlign: 'auto',
                left: 'auto',
                right: '10%',
                top: '10%',
                bottom: 'auto',
                triggerEvent: true
            },
            tooltip: {
                trigger: 'axis',
                showDelay: 0,
                axisPointer: {//悬浮展示数据
                    show: true,
                    type: 'line',
                    lineStyle: {
                        type: 'dashed',
                        width: 1
                    }
                },
                formatter: function (value) {
                    var value = value[0];
                    return value.seriesName + ":" + value.value;

                }
            },
            toolbox: {
                show: false,
                orient: 'vertical',
                left: 'right',
                top: 'center'
            },
            grid: {
                containLabel: true
            },
            calculable: true,
            dataZoom: {
                id: 'dataZoomY',
                show: true,
                realtime: true,
                type: 'inside', // slider表示有滑动块的，inside表示内置的
                //bottom:"5%",
                borderColor: "transparent", // 滚动条边框颜色
                height: 10
            },
            xAxis: [
                {
                    show: true,
                    type: 'category',
                    boundaryGap: true,
                    data: xdata,
                    axisLabel: {
                        showMinLabel: true,
                        showMaxLabel: true,
                    }
                }

            ],
            yAxis: yaxis,
            series: series
        }
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    }
}


/**
 * 通过post方式打开新页面
 * @param url地址
 * @param data参数
 * @param name名称
 */
window.openUrlPost = function (url, data, name) {
    var params = [];
    for (var name in data) {
        params.push({
            name: name,
            value: data[name]
        })
    }
    TempoUtils.PostOpenUrl(url, name, params);
}

/**
 * 信号数据集
 * @param contentTab 当前div
 * @param insightData 信号数据
 * @param isShowWaveFrom 是否展示波形图
 */
window.signalDataShow = function (contentTab, insightData, isShowWaveFrom, insightResItem) {
    //信号模块洞察调整，将波形图和输出数据位置互换
    if (isShowWaveFrom) {
        var waveformGraph = $('<span style="font-weight: bold;padding: 10px; cursor: pointer;font-size:14px;" id="waveformGraph">' + TempoUtils.locale("mine.waveform") + '</span>').appendTo(contentTab);
        waveformGraph.click(function (e) {
            rs.empty();
            inputPanel.css('font-weight', 'normal');
            waveformGraph.css('font-weight', 'bold');
            contentTab.find("#openData").css('display', 'none');
            var formatData = createFormatData(insightData);
            createWaveform(formatData, rs, insightResItem.id);
        });
        setTimeout(function () {
            waveformGraph.trigger("click");
        });
    }
    var inputPanel = $('<span style="padding: 10px; cursor: pointer;display: inline;font-size:14px;" id="inputPanel">' + TempoUtils.locale("mine.originalData") + '</span>').appendTo(contentTab);
    var rs = $('<div id="rs" style="margin-top: 10px;"></div>').appendTo(contentTab);
    if (!isShowWaveFrom) {
        inputPanel.css('font-weight', 'bold');
        createResTable(insightData, rs);
        rs.find('table:eq(0)').css('display', 'block');
        rs.find('table:eq(1)').css('display', 'none');
    }
    inputPanel.click(function (e) {
        rs.empty();
        inputPanel.css('font-weight', 'bold');
        contentTab.find("#openData").css('display', 'block');
        if (waveformGraph) {
            waveformGraph.css('font-weight', 'normal');
        }
        createResTable(insightData, rs);
        setTimeout(function () {
            var openData = $('<span title="查看前100行" style="cursor: pointer;margin-right: 10px;float: right;color: #00CCFF" id="openData">查看数据</span>').insertAfter(contentTab.find("[id^='rowNumberStat']"));
            openData.click(function () {
                var a = TempoUtils.clone(insightData);
                var flowName = "undefined" == typeof (currentInsightFlowName) ? ("undefined" == typeof (snapshotFlow) ? $('.tempo-mine-tab-curSelect').find('label').text() : snapshotFlow.flow.name) : currentInsightFlowName
                if ((!flowName || flowName == null || flowName == "") && $(".navigator-path-text").length > 0) {
                    flowName = $(".navigator-path-text").text();
                }
                a.flowName = flowName;
                a.nodeName = insightResItem.nodeLabel;
                openUrlPost(contextPath + '/api/ai/mine/view/lookData', {'insightdata': JSON.stringify(a)}, TempoUtils.uuid())
            })
        }, 10);
    });
    setTimeout(function () {
        var openData = $('<span title="查看前100行" style="cursor: pointer;margin-right: 10px;float: right;color: #00CCFF" id="openData">查看数据</span>').insertAfter(contentTab.find("[id^='rowNumberStat']"));
        openData.click(function () {
            var a = TempoUtils.clone(insightData);
            var flowName = "undefined" == typeof (currentInsightFlowName) ? ("undefined" == typeof (snapshotFlow) ? $('.tempo-mine-tab-curSelect').find('label').text() : snapshotFlow.flow.name) : currentInsightFlowName
            if ((!flowName || flowName == null || flowName == "") && $(".navigator-path-text").length > 0) {
                flowName = $(".navigator-path-text").text();
            }
            a.flowName = flowName;
            a.nodeName = insightResItem.nodeLabel;
            openUrlPost(contextPath + '/api/ai/mine/view/lookData', {'insightdata': JSON.stringify(a)}, TempoUtils.uuid())
        })
    }, 10);
}
